﻿namespace DesignModeConsole.创建型.单例模式
{
    /// <summary>
    /// 单例模式服务
    /// </summary>
    public class SingletonService : IService
    {
        public void Main()
        {
            /*
             如何实现单例？
            ● 构造函数需要是private访问权限，这样子避免通过外部new创建实例
            ● 考虑对象创建时的线程安全问题
            ● 考虑是否支持延迟加载
            ● 考虑getInstance()性能是否高(是否加锁)
             */

            Test().GetAwaiter().GetResult();

            // 非单例的情况
            var list = Enumerable.Range(0, 10)
                                 .AsParallel()
                                 .Select(t => new Logger())
                                 .Distinct()
                                 .ToList();
            Console.WriteLine($"非单例的情况 {list.Count}");

            // 单例的情况
            var list7 = Enumerable.Range(0, 10)
                                  .AsParallel()
                                  .Select(t => Logger7.GetInstance())
                                  .Distinct()
                                  .ToList();
            Console.WriteLine($"单例的情况 {list7.Count}");
        }

        private async Task Test()
        {
            await Task.Run(AddOrder);

            await Task.Run(AddUser);
        }

        /// <summary>
        /// 模拟添加订单日志
        /// </summary>
        private void AddOrder()
        {
            //ILogger logger = new Logger1();
            ILogger logger = Logger7.GetInstance();
            Console.WriteLine("addorder " + logger.GetHashCode());
            for (var i = 0; i < 100; i++)
            {
                logger.Log($"AddOrder {i}");
            }
        }

        /// <summary>
        /// 模拟添加用户日志
        /// </summary>
        private void AddUser()
        {
            //ILogger logger = new Logger1();
            ILogger logger = Logger7.GetInstance();
            Console.WriteLine("adduser " + logger.GetHashCode());
            for (var i = 0; i < 100; i++)
            {
                logger.Log($"AddUser {i}");
            }
        }
    }
}